<?php

namespace app\model;

use think\helper\Str;
use think\Model;

class Supplier extends Model
{
    public function saveData(): array
    {
        $param = request()->post();
        $count = $this->when(!empty($param['out_key']), function ($query) use ($param) {
            $query->where('out_key', $param['out_key']);
        })->when(!empty($param['id']), function ($query) use ($param) {
            $query->where('id', '<>', $param['id']);
        })->count();
        if ($count > 0) throw new \Exception('渠道账号已存在，请重新填写！');
        if (empty($param['id'])) {
            $pwd = setPassword("123456");
            $param['password'] = $pwd['password'];
            $param['password_token'] = $pwd['token'];
        }
        $this->exists(!empty($param['id']))->save($param);
        return $this->toArray();
    }

    public function pageData(): array
    {
        $param = request()->param();
        $data = $this/*->when(!empty($param['out_key']), function ($query) use ($param) {
            $query->where('out_key', 'like', "%{$param['out_key']}%");
        })*/ ->when(!empty($param['name']), function ($query) use ($param) {
            $query->where('name', 'like', "%{$param['name']}%");
        })->when(!empty($param['mobile']), function ($query) use ($param) {
            $query->where('mobile', $param['mobile']);
        })->order("create_time desc")->paginate(['list_rows' => 30, 'page' => $param['page'] ?? 1])->toArray();
        return pageData($data);
    }

    public function detailData()
    {
        return $this->where('id', request()->param('id'))->find();
    }

    public function balance(): array
    {
        $param = request()->post();
        $data = $this->where('id', $param['id'])->where('state', 1)->find();
        if (empty($data)) throw new \Exception('渠道不存在');
        $this->startTrans();
        if ($param['tag'] == 1) {
            $balance = bcadd($data['balance'], $param['balance'], 2);
        } else {
            $balance = bcsub($data['balance'], $param['balance'], 2);
        }
        $data->save(['balance' => $balance]);
        $user = request()->account ?? [];
        app(SupplierBalanceNotice::class)->save([
            'sid' => $data['id'],
            'admin' => $user['name'] ?? '',
            'tag' => $param['tag'],
            'amount' => $param['amount'],
            'money' => $param['balance'],
            'remark' => $param['remark'] ?? '',
            'order_sn' => date("YmdHis") . Str::random(8, 1),
            'type' => $param['type'],
            'total' => $balance
        ]);
        $this->commit();
        return $data->toArray();
    }

    public function search(): array
    {
        return $this->where('state', 1)->column("id,name,discount", "id");
    }
}
